package dao

import (
	"encoding/json"
	"gitee.com/mangenotwork/game-douniu/api/common"
	"gitee.com/mangenotwork/game-douniu/api/entity"
)

type GameDao struct {
}

func (dao *GameDao) NewGame(data *entity.GameInfoData) (*entity.GameInfoData, error) {
	db := common.GetGorm("test")
	err := db.Model(&entity.GameInfoData{}).Create(data).Error
	return data, err
}

func (dao *GameDao) BalanceRecord(data *entity.UserGameItemInfo) error {
	db := common.GetGorm("test")
	err := db.Model(&entity.UserGameItemInfo{}).Create(data).Error
	return err
}

func (dao *GameDao) GetItemResult(itemId, gameId int64) ([]*entity.UserGameItemInfo, error) {
	db := common.GetGorm("test")
	result := make([]*entity.UserGameItemInfo, 0)
	db = db.Model(&entity.UserGameItemInfo{}).Where("item_id=? and game_id=?", itemId, gameId)
	err := db.Find(&result).Error
	return result, err
}

func (dao *GameDao) GetFinalResult(gameId int64) ([]*entity.UserGameItemInfo, error) {
	db := common.GetGorm("test")
	result := make([]*entity.UserGameItemInfo, 0)
	db = db.Model(&entity.UserGameItemInfo{}).Where("game_id=?", gameId)
	err := db.Find(&result).Error
	return result, err
}

func (dao *GameDao) GetUserGameResult(userId, page, limit int64) (int64, []*entity.UserGameRecord, error) {
	db := common.GetGorm("test")
	result := make([]*entity.UserGameRecord, 0)
	db = db.Model(&entity.UserGameItemInfo{}).Select("user_id, vocation, game_id, created_at, sum(score) as score")
	db = db.Where("user_id=?", userId).Group("game_id").Order("created_at desc")

	var count int64 = 0
	err := db.Count(&count).Error
	if err != nil {
		return count, result, err
	}

	db = db.Scopes(Pagination(int(page), int(limit)))
	err = db.Find(&result).Error
	return count, result, err
}

func (dao *GameDao) UserGameCount(userIds []int64) (map[int64]*entity.UserGameCount, error) {
	db := common.GetGorm("test")
	sqlQuery := "select a.user_id as user_id, count(*) as num from (select user_id from test.user_game_item_info where user_id in (?) group by game_id) as a group by a.user_id;"
	result := make([]*entity.UserGameCount, 0)
	resultMap := make(map[int64]*entity.UserGameCount)
	err := db.Raw(sqlQuery, userIds).Scan(&result).Error
	if err != nil {
		return resultMap, err
	}
	for _, v := range result {
		resultMap[v.UserId] = v
	}
	return resultMap, err
}

func (dao *GameDao) UserGameList(userId int64) ([]*entity.UserGameItemInfo, error) {
	db := common.GetGorm("test")
	result := make([]*entity.UserGameItemInfo, 0)
	err := db.Model(&entity.UserGameItemInfo{}).Where("user_id=?", userId).Order("game_id desc").Find(&result).Limit(500).Error
	return result, err
}

func (dao *GameDao) AnalysisPoker(poker, pokerResult string) ([]*entity.PokerData, *entity.DouNiuResult, error) {
	pokerObj := make([]*entity.PokerData, 0)
	pokerResultObj := &entity.DouNiuResult{}
	err := json.Unmarshal([]byte(poker), &pokerObj)
	err = json.Unmarshal([]byte(pokerResult), &pokerResultObj)
	return pokerObj, pokerResultObj, err
}
